import { ReactNode, createContext, useContext, useReducer } from "react";
import { EditorAction, editorReducer } from "./editor-reducer";
import { Editor } from "../types";
import { MockWidgetList } from "../constants/charts-data-01";
import { getThemeByJson } from "../theme";

/** 编辑器默认初始状态 */
const initEditorStore: Editor = {
  golbalSettings: getThemeByJson("默认"),
  widgetList: MockWidgetList,
  curSelectedWidgetId: null
};

export const EditorContext = createContext<Editor>(initEditorStore);

export const EditorDispatchContext = createContext<
  React.Dispatch<EditorAction>
>(() => {});

function EditorProvider({ children }: { children: ReactNode }) {
  const [editor, dispatch] = useReducer(editorReducer, initEditorStore);

  return (
    <EditorContext.Provider value={editor}>
      <EditorDispatchContext.Provider value={dispatch}>
        {children}
      </EditorDispatchContext.Provider>
    </EditorContext.Provider>
  );
}

function useEditorContext() {
  const editor = useContext(EditorContext);
  const dispatch = useContext(EditorDispatchContext);

  /** 当前选中组件info */
  const curWidgetInfo = editor.widgetList.find(
    (w) => w.id === editor.curSelectedWidgetId
  );

  return { editor, dispatch, curWidgetInfo };
}

export { EditorProvider, useEditorContext };
